<template>
  <section class="detail-container">
    <div class="conflict-box" v-if="!hasData">
      <i class="iconfont icon-clock"></i> <div>oops {{errorMsg}}</div>
    </div>
    <template v-else>
      <div class="password-box" v-if="isPrivate">
        <div class="title">password <span v-if="isWrongPassword">密码错误</span></div>
        <input type="password" placeholder="需要访问密码" v-model="password">
        <div class="btn-confirm" @click="confirm" v-loading="loading">确认</div>
      </div>
      <code-editor @update="confirm" v-loading="loading" v-else v-bind="params"></code-editor>
    </template>

  </section>
</template>
<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { CmOptions } from 'codemirror'
import { getCodeById } from '@/api/code'
import { REQUEST_CODE } from '@/utils/config'
import codeHistory from '@/hooks/codeHistory'
// http://localhost:8888/FUicy0
const route = useRoute()
interface Params {
  id?: string
  code?: string
  title?: string
  options?: CmOptions
  version?: any
}

const params = reactive<Params>({
  title: '',
  code: '',
  options: {
    theme: 'darcula',
    mode: 'Java'
  }
})

const loading = ref(true)
const id = ref<string>(route.params.id as string || '')
const password = ref('')
const isPrivate = ref(false)
const isWrongPassword = ref(false)
const hasData = ref(true)
const errorMsg = ref('')
const {browsingHistoryPush} = codeHistory()
const getCodeDetail = () => {
  getCodeById(id.value, password.value).then(({ data }) => {
    params.id = id.value
    params.code = data.content
    params.title = data.title
    params.version = data.version
    params.options = {
      mode: data.syntax,
      theme: data.style,
      readOnly: !data.editable
    }
    nextTick().then(() => isPrivate.value = false)
    isWrongPassword.value = false
    browsingHistoryPush({
      title: data.title,
      id: data.id
    })
  }).catch(({ code, message }) => {
    if (code === REQUEST_CODE.unauthorized) {
      isPrivate.value = true
    }else if (code === REQUEST_CODE.forbidden){
      isWrongPassword.value = true
    }else if ([REQUEST_CODE.notFound, REQUEST_CODE.conflict].includes(code)){
      hasData.value = false
      errorMsg.value = message
    }
  }).finally(() => {
    loading.value = false
    // const a=  useAppPrompt({
    //   maxlength: 10,
    //   placeholder: 'hahah',
    //   useInput: true,
    //   dialogOptions:{
    //     hideCloseBtn: true,
    //     closeOnClickCover: false
    //   }
    // }).then((res)=>{
    //   console.log(res)
    // })
  })
}
const confirm = ()=>{
  if (!password.value){
    return
  }
  loading.value = true
  getCodeDetail()
}
onMounted(() => {
  getCodeDetail()
})
</script>

<style scoped lang="scss">
@import 'index';
</style>
